import axios from "axios";
import { HOST } from "@/global";
// import { MessageBox, Message } from 'element-ui'
import { Message } from "element-ui";
// import store from '@/store'
import { getToken } from "@/utils/auth";
import { isBlob } from "@/utils/validate";
// import qs from 'qs';
// console.log(qs);

axios.defaults.headers["Content-Type"] = "application/json;";
// axios.defaults.headers['Content-Type'] = 'application/json;'
// axios.defaults.headers['Content-Type'] = 'multipart/form-data;'

// 192.168.1.226 凯洋ip 调试跨域
console.log(`HOST: ${HOST}`);
// create an axios instance
const request = axios.create({
  //   baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  //   baseURL: process.env.NODE_ENV == 'development' ? '/api' : `${HOST}/api`,
  baseURL: process.env.NODE_ENV == "development" ? "/api" : HOST,
  //   baseURL: process.env.NODE_ENV == 'development' ? '/api' : `http://192.168.1.226:8081`,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 20 * 1000, // request timeout
});

// request interceptors
request.interceptors.request.use(
  (config) => {
    // do something before request is sent
    config.method = config.method || "get";
    let getMethod = config.method.toLocaleUpperCase();

    //  添加用户的身份标识
    if (getToken()) {
      config.headers["Authorization"] = `Bearer ${getToken()}`;
    }
    // 如果设置了ContentType，则需要重新设置一下，一般传递的参数为:multipart/form-data
    if (config.ContentType) {
      config.headers["Content-Type"] = config.ContentType;
      delete config.ContentType;
    }

    let getContentType = config.headers["Content-Type"];
    // get请求映射 params 参数
    if (getMethod === "GET" && config.params) {
      //   console.log(`qs(config.params) ======================================= `);
      //   console.log(qs.stringify(config.params));
      console.log(config);
    }
    // console.log(`getMethod: ${getMethod}`)
    // 需要把params 传递给data ， 如果有data ，参数就会在body里边，9200 端口的登录是放在body里边的

    if (getMethod === "POST" || getMethod === "PUT") {
      // 需要把params 传递给data ， 如果有data ，参数就会在body里边，9200 端口的登录是放在body里边的
      config.data = config.params || {};
    }
    // 特殊处理分页， pageNum,pageSize 需要放到url，后端request接受，别的参数还在body体里传输就行
    if (config.params) {
      let { pageNum, pageSize } = config.params;
      if ((pageNum, pageSize)) {
        config.params = {
          pageNum,
          pageSize,
        };
      }
    }
    // 判断是否需要删除 params，避免参数出现在地址栏里报错
    let deleteParamsUrls = [
      "/auth/login",
      "/admin/Task/add",
      "/admin/Task/exit",
      "/admin/strategy/add",
      "/admin/strategy/edit",
      '/edu/questions/add',
      "/edu/strategy/add",
      "/edu/strategy/edit",
      "/admin/chargePlan/add",
      "/admin/chargePlan/edit",
      "/admin/unifiedExamination/results/add",
      "/admin/unifiedExamination/results/edit",
      "/examination/schoolEducation/edit",
      "/auth/logout",
      "/auth/refresh",
      '/admin/room/add',
      "/admin/exam/add",
      '/edu/class/add',
      "/admin/exam/exit",
      "/edu/templat/add",
      "/admin/templat/add",
      "/admin/templat/edit",
      '/admin/grade/add',
      "/edu/teacher/add",
      '/admin/room/edit',
      '/admin/graduate/add',
      '/admin/graduate/edit',
      '/admin/AdmissionScheme/exit',
      "/edu/teacher/info",
      '/admin/AdmissionScheme/add',
      '/edu/teacher/edit',
      "/edu/questions/add",
      '/admin/graduate/screening',
      '/edu/questions/edit',
      '/admin/charges/add',
      '/edu/colleage/edit',
      "/teacher/addpost/add",
      '/admin/signForm/printf',
      '/edu/schoolSemester/add',
      '/admin/questionnaire/add',
      '/admin/questionnaire/edit',
      "/edu/paperManagement/add",
      "/admin/gradeStandard/add",
      "/admin/gradeStandard/edit",
      '/edu/paperManagement/rules/update',
      "/edu/schoolEducation/edit",
      "/edu/questions/questionsId",
      "/edu/paperManagement/update",
      "/edu/schoolYearSemester/add",
      "/edu/schoolYearSemester/edit",
      '/edu/basicManagement/plan/add',
      "/edu/paperManagement/rules/add",
      '/edu/basicManagement/plan/edit',
      '/examination/SelfCertificate/add',
      '/examination/SelfQuestionnaire/add',
      // "/edu/paperManagement/rules/list",
      "/edu/schoolYearSemester/editStatus",
      "/edu/electronicPhotoStrategy/export",
      '/examination/studentAchievementManage/add',
      "/admin/studentAchievementManage/add",
      "/admin/studentAchievementManage/edit",
      "/edu/basicManagement/scheduleCourseDetail/schedule-course-save",
      '/admin/Certificate/add'
    ];
    if (
      deleteParamsUrls.includes(config.url) ||
      getContentType == "multipart/form-data"
    ) {
      delete config.params;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// response interceptor
request.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data;
    console.log(`劫持响应函数`);
    console.log(res);

    // const loginHOST = "http://192.168.1.155:9200" 登录接口的code 是200，别的接口的code 是0，所以暂时两个 都判断一下
    if (res.code == 0 || res.code == 200) {
      /* Message({
              message: res.msg || 'ok',
              type: 'ok',
              duration: 2 * 1000
            }) */
    } else if (isBlob(res)) {
      // 特殊判断是否为 blob对象，如果是则说明是下载或者导出功能
      Message({
        message: "下载成功~",
        type: "ok",
        duration: 2 * 1000,
      });
    } else {
      Message({
        message: res.msg || "error",
        type: "error",
        duration: 3 * 1000,
      });
    }

    // if the custom code is not 20000, it is judged as an error.
    /* if (res.code !== 20000) {
            Message({
                message: res.message || 'Error',
                type: 'error',
                duration: 5 * 1000
            })

            // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
            if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
                // to re-login
                MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
                    confirmButtonText: 'Re-Login',
                    cancelButtonText: 'Cancel',
                    type: 'warning'
                }).then(() => {
                    store.dispatch('user/resetToken').then(() => {
                        location.reload()
                    })
                })
            }
            return Promise.reject(new Error(res.message || 'Error'))
        } else {
            return res
        } */
    return res;
  },
  (error) => {
    // console.log('err' + error) // for debug
    Message({
      message: error.msg || "error",
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default request;
